#pragma strict

var crosshair : Texture;
//Game Objects
private var scriptsGObj : GameObject;

//components
private var BZ3UtilsComponent : BZ3Utils;

//Resolutions
private var actualSetResolution : Resolution;
private var resolutions : Resolution[];

//button stuff
private var buttonSizeX = 80;
private var buttonSizeY = 30;
private var optionButtonPressed = false;
private var scoreboardButtonPressed = false;

//dropdown menu
private var showList : boolean = false;
private static var listEntrySelected : int;
private static var listEntry : int = 2;
private static var defaultEntryNumber : int = 0;
private var listColours : GUIContent[];
private var generalListStyle : GUIStyle = new GUIStyle();
private var dropdownListHash : int;

//scoreboard
private var scoreBoardTime : float = 15.0; //time to wait until next db request
private var scoreBoardTimer : float = scoreBoardTime;
private var rssTime : float;
private var scoreBoard : String = "";

//player related
private var playerName : String;
private var playerPoints : int;
private var playerLifes : int;
private var playerDamage : int;
private var pNameInputString : String = "";

private var isSaveMenueActive = false;

function Start(){
	scriptsGObj = GameObject.FindGameObjectWithTag("Scripts");
    
    BZ3UtilsComponent = scriptsGObj.GetComponent(BZ3Utils);
    
    resolutions = Screen.resolutions;
    actualSetResolution = Screen.currentResolution;
    
    //dropdown menu content
	listColours = new GUIContent[resolutions.length];
	
	//Given resolutions in the list
	for(var i : int = 0; i<resolutions.length; i++){
		listColours[i] = new GUIContent(resolutions[i].width + " x " + resolutions[i].height);
	}
	
	generalListStyle.padding.left = generalListStyle.padding.right = generalListStyle.padding.top = generalListStyle.padding.bottom = 4;
	dropdownListHash = "DropdownList".GetHashCode();
}

function Update(){
	//Get the GameObject and the Component Script on it and the playername throu the function.
	playerName = scriptsGObj.GetComponent(Player).getPlayerName();
	playerPoints = scriptsGObj.GetComponent(Player).getPlayerScore();
}

function createHUDGUI(){
	playerDamage = scriptsGObj.GetComponent(Player).getPlayerDamage();
	playerLifes = scriptsGObj.GetComponent(Player).getPlayerLifes();
	
	Crosshair((Screen.width/2),(Screen.height/2));	//create the crosshair
	HUD();
}

public function Crosshair(w2 : int,h2 : int){
    if(!crosshair){
		Debug.LogError("Assign a Texture in the inspector.");
		return;
	}
	GUI.DrawTexture(new Rect(w2-50,h2-50,100,100), crosshair, ScaleMode.StretchToFill, true, 10.0f);
}

public function HUD(){
	if(playerLifes>0){
		GUILayout.BeginHorizontal();
		
	    GUILayout.Label("Damage: ");
	    GUILayout.TextField("" + playerDamage);
	    
	    GUILayout.Label("Lifes: ");
	    GUILayout.TextField("" + playerLifes);
	    
	    GUILayout.Label("Points: ");
    	GUILayout.TextField("" + playerPoints);
	    
	    GUILayout.EndHorizontal();
	}
}


function createMenuGUI(){
    // display Menu
    if(optionButtonPressed){
    	displayOptionsMenuGUI();
    }else if(scoreboardButtonPressed){
    	displayScoreboardGUI();
    }else if(isSaveMenueActive){
    	saveMenue();
    }else{
    	displayMenuGUI();
    }
}
 
function displayMenuGUI(){
    //Button-Menue
    GUILayout.BeginArea(new Rect((Screen.width/2)-buttonSizeX/2,(Screen.height/2)-buttonSizeY*2,buttonSizeX,buttonSizeY*6)); //Number of buttons+1
    GUILayout.BeginVertical();
    
	if (GUILayout.Button("Resume", GUILayout.Width(buttonSizeX), GUILayout.Height(buttonSizeY))){
		Debug.Log("Resuming game.");
		scriptsGObj.SendMessage("setGUIEnabled", false);
	}
	if (GUILayout.Button("Scoreboard", GUILayout.Width(buttonSizeX), GUILayout.Height(buttonSizeY))){
		Debug.Log("Open Scoreboard.");
		scoreboardButtonPressed = true;
	}
	if (GUILayout.Button("Restart", GUILayout.Width(buttonSizeX), GUILayout.Height(buttonSizeY))){
		Debug.Log("Restarting game.");
		scriptsGObj.SendMessage("setGUIEnabled", false);
		
		Application.LoadLevel("Battlezone3D");
		scriptsGObj.SendMessage("ResetPlayerStats");
	}
	if (GUILayout.Button("Options", GUILayout.Width(buttonSizeX), GUILayout.Height(buttonSizeY))){
		Debug.Log("Open options.");
		optionButtonPressed = true;
	}
	if (GUILayout.Button("Quit", GUILayout.Width(buttonSizeX), GUILayout.Height(buttonSizeY))){
		Debug.Log("Exeting game.");
		//Only works as richclient (local application)
		Application.CancelQuit();
	}
	
	GUILayout.EndVertical();
	GUILayout.EndArea();
}

public function setScoreboard(value : String){
	scoreBoard = value;
}

function displayScoreboardGUI(){
	
	//For indipendent time management from fps and Time.timescale=0
	if(scoreBoardTimer == scoreBoardTime){
		scriptsGObj.GetComponent(HighscoreController).getScores();
		rssTime = Time.realtimeSinceStartup;
		scoreBoardTimer = 0;
	}else if((Time.realtimeSinceStartup - rssTime) > scoreBoardTime){
		scoreBoardTimer = scoreBoardTime;
	}

	GUILayout.BeginHorizontal();
	
    GUILayout.Label("Scoreboard: ");
    GUILayout.TextField(scoreBoard);
    
    GUILayout.EndHorizontal();

    
    GUILayout.BeginArea(new Rect((Screen.width/2)-buttonSizeX/2,(Screen.height/2)-buttonSizeY*2,buttonSizeX,buttonSizeY*6)); //Number of buttons+1
    GUILayout.BeginVertical();
    
	if (GUILayout.Button("Close", GUILayout.Width(buttonSizeX), GUILayout.Height(buttonSizeY))){
		Debug.Log("Closing Options.");
		scoreboardButtonPressed = false;
	}
	
	GUILayout.EndVertical();
	GUILayout.EndArea();
}

private var buttonCount : int = 2;

function displayOptionsMenuGUI(){
	//Rect(x position,y position, x size, y size)
	GUILayout.BeginArea(new Rect((Screen.width/2)-buttonSizeX/2, (Screen.height/2)-buttonSizeY*2, Screen.width, Screen.height)); //Number of buttons+1
    GUILayout.BeginVertical();
    
	if (GUILayout.Button("Close", GUILayout.Width(buttonSizeX), GUILayout.Height(buttonSizeY))){
		Debug.Log("Closing Options.");
		optionButtonPressed = false;
	}
	
	if (GUILayout.Button("Fullscreen", GUILayout.Width(buttonSizeX), GUILayout.Height(buttonSizeY))){
		Debug.Log("Toggle fullscreen.");
		if(Screen.fullScreen){
			Screen.SetResolution(actualSetResolution.width, actualSetResolution.height, false);
		}else{
			Screen.SetResolution(actualSetResolution.width, actualSetResolution.height, true);
		}
	}
	
	if(GUILayout.Button("+ Quality", GUILayout.Width(buttonSizeX), GUILayout.Height(buttonSizeY))){
		QualitySettings.IncreaseLevel(true);
	}
	if(GUILayout.Button("- Quality", GUILayout.Width(buttonSizeX), GUILayout.Height(buttonSizeY))){
		QualitySettings.DecreaseLevel(true);
	}
	
	//dropdown menu
	//Rect(x position,y position, x size, y size) (buttonSizeY+4)*buttonCount
	DropDownMenue(Rect(buttonSizeX + 4, 0, buttonSizeX, buttonSizeY), showList, listEntry, GUIContent(listColours[listEntrySelected].text), listColours, "button", generalListStyle);
	
	GUILayout.EndVertical();
	GUILayout.EndArea();
}

public function setSaveMenueActive(){
	isSaveMenueActive = true;
}

public function getSaveMenueActive() : boolean{
	return isSaveMenueActive;
}

public function saveMenue(){
	GUILayout.BeginHorizontal();
	
	GUILayout.Label("Game Over! Enter your name for the highscore: ");
    pNameInputString = GUILayout.TextField(pNameInputString, 3, GUILayout.Width(30));
    
	GUILayout.EndHorizontal();
	
	
	GUILayout.BeginArea(new Rect((Screen.width/2)-buttonSizeX/2,(Screen.height/2)-buttonSizeY*2,buttonSizeX,buttonSizeY*6)); //Number of buttons+1
    GUILayout.BeginVertical();
    
    if(!pNameInputString.Equals("")){
    	if (GUILayout.Button("Save", GUILayout.Width(buttonSizeX), GUILayout.Height(buttonSizeY))){
			Debug.Log("Saving Options.");
			
			//Persist player name and score in database.
			scriptsGObj.GetComponent(HighscoreController).postScore(pNameInputString, playerPoints);
		}
    }
	if (GUILayout.Button("New Game", GUILayout.Width(buttonSizeX), GUILayout.Height(buttonSizeY))){
		Debug.Log("Closing Options.");
		
		isSaveMenueActive = false;
		
		//Dont put it after the persist! Or it will not persist, dono why?!?
		Application.LoadLevel("Battlezone3D"); //TODO outsource !?!
	}
	
	GUILayout.EndVertical();
	GUILayout.EndArea();
}


//creates a drop down menue
function DropDownMenue(position:Rect, expandList:boolean, listEntry:int, defaultListEntry:GUIContent, listToUse:GUIContent[], buttonStyle:GUIStyle, listStyle:GUIStyle){
  
  var controlID : int = GUIUtility.GetControlID(dropdownListHash, FocusType.Passive);
  var done : boolean = false;
  
  if(Event.current.GetTypeForControl(controlID) == EventType.mouseDown){
	if (position.Contains(Event.current.mousePosition)){
        GUIUtility.hotControl = controlID;
        showList = !showList;
    }
  }
    
  if(Event.current.GetTypeForControl(controlID) == EventType.mouseDown && !position.Contains(Event.current.mousePosition)){
    GUIUtility.hotControl = controlID;
  }               
  
  GUI.Label(position, defaultListEntry, buttonStyle);
  
  if(expandList){
	  //list box settings
	  listStyle.normal.textColor = Color.green;
	  var listRect : Rect = new Rect(position.x, position.y + buttonSizeY + 4, position.width, listStyle.CalcHeight(listToUse[0], 1.0f) * listToUse.Length);
	  
	  GUI.enabled = false;
	  GUI.Button(listRect, "");
	  GUI.enabled = true;
	  GUI.Box(listRect, "", "box");
	  
	  listEntrySelected = GUI.SelectionGrid(listRect, listEntrySelected, listToUse, 1, listStyle);
	  listEntry = listEntrySelected;
	  
	  if(listEntrySelected != defaultEntryNumber && !position.Contains(Event.current.mousePosition)){
	    GUIUtility.hotControl = controlID;
	    showList = !showList;
	  	defaultEntryNumber = listEntrySelected;
	  	
	  	Screen.SetResolution(resolutions[listEntrySelected].width, resolutions[listEntrySelected].height, Screen.fullScreen);
	  	actualSetResolution = Screen.currentResolution;
	  }    
  }
}